import { Component, OnInit, Output, EventEmitter, Input } from '@angular/core'
import { CommonUtil } from 'src/app/common/utils/common.util'
import { CoolLocalStorage } from 'src/app/common/coolStorage/cool-local-storage'

@Component({
  selector: 'cp-estate-filter',
  templateUrl: './estate-filter.component.html',
  styleUrls: ['./estate-filter.component.scss']
})
export class EstateFilterComponent implements OnInit {
  @Input() cpParams
  @Output() onGenerate = new EventEmitter()

  // 区域模态框是否展示
  areaShow = false
  // 区域类型(1区域 2地铁 3附近)
  areaType = 1
  // areaText
  areaText = '区域'
  // 二级菜单选择项
  middleSelected: any = {
    Landmarks: [],
    Stations: []
  }
  // 三级菜单选择项
  innerValue = []
  // 最终的lambda表达式
  areaLambda = ''
  // 最终的排序数据
  areaSorter
  // 可筛选的区域列表数据
  areaData = {
    region: [],
    metro: [],
    nearby: [
      { Value: 0, Name: '不限' },
      { Value: 1000, Name: '1000米内' },
      { Value: 2000, Name: '2000米内' },
      { Value: 3000, Name: '3000米内' },
      { Value: 5000, Name: '5000米内' }
    ]
  }

  // 价格模态框是否展示
  priceShow = false
  // 价格类型(1单价 2总价)
  priceType = 1
  // 当前选择
  priceValue = { key: null, value: '不限' }
  // 可输入的最小价格
  minPrice
  // 可输入的最大价格
  maxPrice
  // 最终的lambda表达式
  priceLambda = ''
  // 可筛选的价格列表数据
  priceData = {
    single: [
      { key: null, value: '不限' },
      { key: [0, 7000], value: '7000以下' },
      { key: [7000, 9000], value: '7-9千' },
      { key: [9000, 10000], value: '9千-1万' },
      { key: [10000, 15000], value: '1-1.5万' },
      { key: [15000, 0], value: '1.5万以上' }
    ],
    muilty: [
      { key: null, value: '不限' },
      { key: [0, 600000], value: '60万以下' },
      { key: [600000, 800000], value: '60-80万' },
      { key: [800000, 1000000], value: '80-100万' },
      { key: [1000000, 1500000], value: '100-150万' },
      { key: [1500000, 2000000], value: '150-200万' },
      { key: [2000000, 0], value: '200万以上' }
    ]
  }

  // 户型模态框是否展示
  layoutShow = false
  // 筛选栏的值
  layoutText = '户型'
  // 最终值
  layoutValue = []
  // 最终的lambda表达式
  layoutLambda = ''
  // 可筛选的户型模态框数据
  layoutData = [
    { key: '1', value: '一居室' },
    { key: '2', value: '二居室' },
    { key: '3', value: '三居室' },
    { key: '4', value: '四居室' },
    { key: '5+', value: '五室及以上' }
  ]

  // 更多模态框
  moreShow = false
  // 最终值
  moreValue = {
    'CategoryInfo.Code': [],
    Area: [],
    'StatusInfo.Code': [],
    Tag: [],
    'DecorationInfo.Code': [],
    Sorter: {}
  }
  // 筛选栏文字
  moreText = '更多'
  // 最终的lambda表达式
  moreLambda = ''
  // 最终的排序表达式
  moreSorter
  // 可筛选的更多数据
  moreData = [
    {
      title: '类型',
      alias: 'CategoryInfo.Code',
      children: [
        { key: 'LayoutCategory_Residence', value: '普通住宅' },
        { key: 'LayoutCategory_Villa', value: '别墅' },
        { key: 'LayoutCategory_Commerce', value: '商住公寓' },
        { key: 'LayoutCategory_Shop', value: '市场商铺' },
        { key: 'LayoutCategory_Office', value: '写字楼' }
      ]
    },
    {
      title: '面积(平米)',
      alias: 'Area',
      children: [
        { key: [0, 60], value: '60以下' },
        { key: [60, 90], value: '60-90' },
        { key: [90, 120], value: '90-120' },
        { key: [120, 150], value: '120-150' },
        { key: [150, 0], value: '150以上' }
      ]
    },
    {
      title: '销售状态',
      alias: 'StatusInfo.Code',
      children: [
        { key: 'SaleStatus_Sell', value: '在售' },
        { key: 'SaleStatus_Wait', value: '待售' },
        { key: 'SaleStatus_Finish', value: '售罄' }
      ]
    },
    {
      title: '楼盘特色',
      alias: 'Tag',
      children: [
        { key: '优选楼盘', value: '优选楼盘' },
        { key: '最近开盘', value: '最近开盘' },
        { key: '花园洋房', value: '花园洋房' },
        { key: '车位充足', value: '车位充足' }
      ]
    },
    {
      title: '装修',
      alias: 'DecorationInfo.Code',
      children: [
        { key: 'LayoutDecoration_1', value: '毛坯' },
        { key: 'LayoutDecoration_2', value: '简装' },
        { key: 'LayoutDecoration_3', value: '精装' }
      ]
    }
  ]
  // 可筛选的排序数据
  moreSortData = [
    { key: '', value: '默认排序' },
    { key: ['AveragePrice', 'Ascending'], value: '均价从低到高' },
    { key: ['AveragePrice', 'Descending'], value: '均价从高到低' }
  ]
  constructor(private utils: CommonUtil, private storage: CoolLocalStorage) {}

  ngOnInit() {
    let params = this.cpParams
    this.getAreaData()
    if (params) {
      let type = params.type
      let obj = { key: params.key, value: params.value }
      this.selectMore(type, obj)
      this.confirmMore()
    }
  }

  // 打开模态框
  toggleShow(e) {
    let list = ['areaShow', 'priceShow', 'layoutShow', 'moreShow']
    // 参数错误
    if (list.indexOf(e) === -1) {
      return false
    }
    // 当前模态框已打开，再次点击就关闭
    if (this[e]) {
      this[e] = false
      return false
    }
    for (let i = 0; i < list.length; i++) {
      let key = list[i]
      if (e === list[i]) {
        this[key] = true
      } else {
        this[key] = false
      }
    }
  }
  // 地域数据
  getAreaData() {
    let region: any = this.storage.getObject('region')
    let metro: any = this.storage.getObject('metro')
    if (region) {
      this.areaData.region = region
    }
    if (metro) {
      this.areaData.metro = metro
    }
  }
  // 区域-选择区域
  selectAreaType(e) {
    this.areaType = Number(e)
    this.middleSelected = {}
    this.innerValue = []
  }
  // 区域/地铁-选择二级
  selectMiddle(item) {
    this.middleSelected = item
    this.innerValue = []
  }
  // 区域/地铁/附近-选择三级
  selectInner(item) {
    let value = this.innerValue
    // 说明是不限
    if (item.Name === '不限') {
      value = []
    } else if (value.length === 0) {
      // 说明第一次点击
      value = [item.Name]
    } else {
      let index = value.indexOf(item.Name)
      // 说明点击目标已经被选择，需要删除
      // 否则就添加到最终结果的数组
      if (index > -1) {
        value.splice(index, 1)
      } else {
        value.push(item.Name)
      }
    }
    this.innerValue = value
  }
  // 重置
  resetArea() {
    this.areaType = 1
    this.middleSelected = {}
    this.innerValue = []
  }
  // 确定筛选
  confirmArea() {
    let text = this.areaText
    let middle: any = this.middleSelected
    let inner: any = this.innerValue
    let location: any = this.storage.getObject('location') || null
    let lambda
    let sorter
    if (this.areaType === 1) {
      // 不限
      if (!middle.Value) {
        lambda = ''
      } else {
        text = middle.Name
        let base = `item.ProjectInfo.Region=="${middle.Name}"`
        let data = inner.map(item => {
          return `item.ProjectInfo.Landmark.Contains("${item}")`
        })
        if (data.length > 0) {
          lambda = `(${base}&&(${data.join('||')}))`
        } else {
          lambda = `(${base})`
        }
      }
    } else if (this.areaType === 2) {
      // 不限
      if (!middle.Value) {
        lambda = ''
      } else {
        text = middle.Name
        let base = `item.ProjectInfo.Metro.Contains("${middle.Name}")`
        let data = inner.map(item => {
          return `item.ProjectInfo.Metro.Contains("${middle.Name}_${item}")`
        })
        if (data.length > 0) {
          lambda = `(${data.join('||')})`
        } else {
          lambda = `(${base})`
        }
      }
    } else if (this.areaType === 3) {
      if (!middle.Name || middle.Name === '不限' || !location) {
        lambda = ''
      } else {
        lambda = `(item.ProjectInfo.Location.Distance(DbGeography.PointFromText("POINT(${location.latitude} ${
          location.longitude
        })",4326))<=${middle.Value})`
        sorter = {
          Property: `item=>item.ProjectInfo.Location.Distance(DbGeography.PointFromText("POINT(${location.latitude} ${
            location.longitude
          })", 4326))`,
          Direction: 'Ascending'
        }
      }
    }
    this.areaText = text
    this.areaLambda = lambda
    this.areaSorter = sorter
    this.generateLambdaAndSorter()
    this.toggleShow('areaShow')
  }

  // 价格-选择单价总价
  selectPriceType(e) {
    this.minPrice = ''
    this.maxPrice = ''
    this.priceValue = { key: null, value: '不限' }
    this.priceType = Number(e)
  }
  // 价格-勾选价格
  selectPriceItem(item) {
    let lambda
    this.priceValue = item
    // 不限
    if (!item.key) {
      lambda = ''
    } else if (item.key[1] === 0) {
      // 说明是xx以上
      if (this.priceType === 1) {
        // 说明是单价
        lambda = `(item.ProjectInfo.Layout.Any(layout=>layout.Area>0&&(double)layout.Price/layout.Area>=${
          item.key[0]
        }))`
      } else {
        // 说明是总价
        lambda = `(item.ProjectInfo.Layout.Any(layout=>layout.Price>=${item.key[0]}))`
      }
    } else {
      // 说明是一个范围
      if (this.priceType === 1) {
        // 说明是单价
        lambda = `(item.ProjectInfo.Layout.Any(layout=>layout.Area>0&&(double)layout.Price/layout.Area>=${
          item.key[0]
        }&&layout.Area>0&&(double)layout.Price/layout.Area<=${item.key[1]}))`
      } else {
        // 说明是总价
        lambda = `(item.ProjectInfo.Layout.Any(layout=>layout.Price>=${item.key[0]}&&layout.Price<=${item.key[1]}))`
      }
    }
    this.priceLambda = lambda
    this.generateLambdaAndSorter()
    this.toggleShow('priceShow')
  }
  // 价格-确定选择
  confirmPrice() {
    let min = Number(this.minPrice)
    let max = Number(this.maxPrice)
    let precent = this.priceType === 1 ? 1 : 10000
    let unit = this.priceType === 1 ? '元' : '万元'
    if (min >= max) {
      this.utils.info('最低价不能高于最高价')
    } else {
      let obj = { key: [min * precent, max * precent], value: `${min}-${max}${unit}` }
      this.selectPriceItem(obj)
    }
  }

  // 户型-勾选户型
  selectLayoutItem(item) {
    let value = this.layoutValue
    // 说明是不限
    if (item.key === '0') {
      value = []
    } else if (value.length === 0) {
      // 说明第一次点击
      value = [item.key]
    } else {
      let index = value.indexOf(item.key)
      // 说明点击目标已经被选择，需要删除
      // 否则就添加到最终结果的数组
      if (index > -1) {
        value.splice(index, 1)
      } else {
        value.push(item.key)
      }
    }
    this.layoutValue = value
  }
  // 户型-确定选择
  confirmLayout() {
    let lambda
    let text = this.layoutText
    let value = this.layoutValue
    // 不限
    if (value.length === 0) {
      lambda = ''
      text = '户型'
    } else {
      if (value.length === 1) {
        text = this.utils.getValueByKey(value[0], this.layoutData)
      } else {
        text = '多选'
      }
      let result = value.map(item => {
        if (item === '5+') {
          return `item.ProjectInfo.Layout.Any(layout=>layout.Room>=5)`
        } else {
          return `item.ProjectInfo.Layout.Any(layout=>layout.Room==${Number(item)})`
        }
      })
      lambda = `(${result.join('||')})`
    }
    this.layoutText = text
    this.layoutLambda = lambda
    this.generateLambdaAndSorter()
    this.toggleShow('layoutShow')
  }

  // 更多选择
  selectMore(alias, value) {
    this.checkArray(value, this.moreValue[alias])
  }
  // 选择排序方式
  selectSorter(e) {
    if (this.moreValue.Sorter['value'] === e.value) {
      this.moreValue.Sorter = {}
    } else {
      this.moreValue.Sorter = e
    }
    // 把其他的激活状态都取消
    let data = this.moreSortData.map(item => {
      if (item.value === e.value) {
        item['active'] = !item['active']
      } else {
        item['active'] = false
      }
      return item
    })
    this.moreSortData = data
  }
  // 数组操作，有a的话就删除，没有就push
  checkArray(item, array) {
    let flag = false
    for (let i = 0; i < array.length; i++) {
      if (item.key === array[i].key) {
        flag = true
        array.splice(i, 1)
        this.setMoreActive(item, false)
      }
    }
    if (!flag) {
      array.push(item)
      this.setMoreActive(item, true)
    }
  }
  // 给更多筛选设置样式
  setMoreActive(item, status) {
    let data = this.moreData
    for (let i = 0; i < data.length; i++) {
      for (let j = 0; j < data[i].children.length; j++) {
        if (item.key === data[i].children[j].key) {
          data[i].children[j]['active'] = status
        }
      }
    }
  }
  // 重置更多
  resetMore() {
    let data = this.moreData
    let moreSortData = this.moreSortData
    this.moreValue = {
      'CategoryInfo.Code': [],
      Area: [],
      'StatusInfo.Code': [],
      Tag: [],
      'DecorationInfo.Code': [],
      Sorter: {}
    }
    this.moreLambda = ''
    for (let i = 0; i < data.length; i++) {
      for (let j = 0; j < data[i].children.length; j++) {
        data[i].children[j]['active'] = false
      }
    }
    for (let k = 0; k < moreSortData.length; k++) {
      moreSortData[k]['active'] = false
    }
    this.moreData = data
    this.moreSortData = moreSortData
  }
  // 确认更多
  confirmMore() {
    let value = this.moreValue
    let lambda = []
    let sorter
    let tempText = []
    // 类型
    if (value['CategoryInfo.Code'].length > 0) {
      let data = value['CategoryInfo.Code'].map(item => {
        tempText.push(item.value)
        return `item.ProjectInfo.Layout.Any(layout=>layout.CategoryInfo.Code.Contains("${item.key}"))`
      })
      let str = `(${data.join('||')})`
      lambda.push(str)
    }
    // 面积
    if (value['Area'].length > 0) {
      let data = value['Area'].map(item => {
        tempText.push(item.value)
        // 说明是xx以上那种类型
        if (item.key[1] === 0) {
          return `(item.ProjectInfo.Layout.Any(layout=>layout.Area>=${item.key[0]}))`
        } else {
          return `(item.ProjectInfo.Layout.Any(layout=>layout.Area>=${item.key[0]}&&layout.Area<=${item.key[1]}))`
        }
      })
      let str = `(${data.join('||')})`
      lambda.push(str)
    }
    // 销售状态
    if (value['StatusInfo.Code'].length > 0) {
      let data = value['StatusInfo.Code'].map(item => {
        tempText.push(item.value)
        return `item.ProjectInfo.StatusInfo.Code.Contains("${item.key}")`
      })
      let str = `(${data.join('||')})`
      lambda.push(str)
    }
    // 楼盘特色
    if (value['Tag'].length > 0) {
      let data = value['Tag'].map(item => {
        tempText.push(item.value)
        return `item.ProjectInfo.Tag.Contains("${item.key}")`
      })
      let str = `(${data.join('||')})`
      lambda.push(str)
    }
    // 装修
    if (value['DecorationInfo.Code'].length > 0) {
      let data = value['DecorationInfo.Code'].map(item => {
        tempText.push(item.value)
        return `item.ProjectInfo.Layout.Any(layout=>layout.DecorationInfo.Code.Contains("${item.key}"))`
      })
      let str = `(${data.join('||')})`
      lambda.push(str)
    }
    if (value['Sorter']['value']) {
      // 不是默认排序，才需要生成排序条件
      if (value['Sorter']['key'] !== '') {
        sorter = {
          Property: `item=>item.ProjectInfo.${value['Sorter']['key'][0]}`,
          Direction: value['Sorter']['key'][1]
        }
      }
    }
    if (lambda.length > 0) {
      this.moreLambda = `(${lambda.join('&&')})`
    }
    if (tempText.length === 0) {
      this.moreText = '更多'
    } else if (tempText.length === 1) {
      this.moreText = tempText[0]
    } else {
      this.moreText = '多选'
    }
    this.moreSorter = sorter
    this.generateLambdaAndSorter()
    this.moreShow = false
  }

  // 生成最终的lambda表达式和排序条件
  generateLambdaAndSorter() {
    let start = this.utils.time2UTC(new Date())
    let end = this.utils.time2UTC(new Date())
    let zone = this.storage.getItem('zone')

    let baseLambda = `item=>item.Publish&&item.Start<=${start}&&item.End>=${end}&&item.Zone==${zone}`
    let baseSorter = [
      { Property: 'item=>item.Sort', Direction: 'Descending' },
      { Property: 'item=>item.Id', Direction: 'Descending' }
    ]

    let arr1 = [this.areaLambda, this.priceLambda, this.layoutLambda, this.moreLambda]
    let arr2 = [this.areaSorter, this.moreSorter]
    let lambda = arr1.filter(item => {
      if (item) {
        return item
      }
    })
    let sorter = arr2.filter(item => {
      if (item) {
        return item
      }
    })
    let Lambda, Sorters
    if (lambda.length > 0) {
      Lambda = baseLambda + '&&' + lambda.join('&&')
    } else {
      Lambda = baseLambda
    }
    if (sorter) {
      Sorters = sorter.concat(baseSorter)
    } else {
      Sorters = baseSorter
    }
    this.onGenerate.emit({ Lambda: Lambda, Sorter: Sorters })
  }
}
